Contents
  1. 1. Introduction
  2. 2. 解决方法
    1. 2.1. 方法一
    2. 2.2. 方法二
  3. 3. 问题
  4. 4. PS
  5. 5. OVER

Introduction

leetcode中的word ladder需要对String变量中的某一个字符进行替换,而String对象在java中是不可改变的。这就需要通过新建字符串进行替换。

解决方法

方法一

可以使用substring方法,截取原有String,再拼接起来。例如如下代码

1
2
3
4
5
String strCurrent = "zhelsihigeyige";
int i = 2;
char c = 'c';
String newString2 = strCurrent.substring(0,i) + c + strCurrent.substring(i + 1);
//result: newString2 == zhclsihigeyige

方法二

String转换成char数组,替换后再新建。例如:

1
2
3
4
5
6
7
String strCurrent = "zhelsihigeyige";
int i = 2;
char c = 'c';
char[] chars = strCurrent.toCharArray();
chars[i] = c;
String newString1 = new String(chars);
//result: newString2 == zhclsihigeyige

问题

但是word ladder题目中,方法一总是超时,方法二却能通过,如此一来,可能是方法一的用时过长。

为测试用时时长,需要利用时间函数,根据测试,时间精确到毫秒,不能检测出其差距,需要更加精准的时间函数,因此选择System.nanoTime()来获取纳秒时间,有如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
String strCurrent = "zhelsihigeyige";
int i = 2;
char c = 'c';
long time1begin = System.nanoTime();
char[] chars = strCurrent.toCharArray();
chars[i] = c;
String newString1 = new String(chars);
long time1end = System.nanoTime();
System.out.println(newString1);
System.out.println(time1end - time1begin);
long time2begin = System.nanoTime();
String newString2 = strCurrent.substring(0,i) + c + strCurrent.substring(i + 1);
long time2end = System.nanoTime();
System.out.println(newString2);
System.out.println(time2end - time2begin);
/**
*zhclsihigeyige
*11794
*zhclsihigeyige
*70483
*/

可见方法二的时间在纳秒级别上比方法一要快很6倍左右。

PS

System.currentTimeMillis()获取的时间精度不一定是1ms,这需要根据具体的机器来判断。原因见文章链接.

OVER

Contents
  1. 1. Introduction
  2. 2. 解决方法
    1. 2.1. 方法一
    2. 2.2. 方法二
  3. 3. 问题
  4. 4. PS
  5. 5. OVER